<template>
  <div>
    <div
      class="all"
      v-show="!dialogVisible"
    >
      <div class="search_box">
        <div>
          <div class="search_title">创建时间</div>
          <div>
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              size="default"
              @change="debouncedSearch"
            />
          </div>
        </div>
      </div>
      <div class="line"></div>
      <div class="button_box">
        <el-button type="primary" class="butten" @click="adds()">新增</el-button>
        <el-button type="danger" class="butten" @click="deleteSelectedRows">
          批量删除
        </el-button>
      </div>
      <div class="table_box">
        <el-table
          v-loading="loading"
          :data="paginatedData"
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="120" align="center">
            <template #default="scope">{{ scope.row.id }}</template>
          </el-table-column>
          <el-table-column label="轮播显示" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.showBoolean"  @change="changeSwitch(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column property="address" label="图片" align="center">
            <template #default="scope">
              <el-image
               
                class="imgs"
                :src="url + scope.row.img"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[url + scope.row.img]"
                :initial-index="4"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column property="updatetime" label="创建时间" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text @click="editRow(scope.row)">编辑</el-button>
              <el-button type="danger" text @click="deleteRow(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :disabled="loading"
          />
        </div>
      </div>
    </div>
    <div v-show="dialogVisible" class="dialog-mask"></div>

    <div
      class="windows"
      v-show="dialogVisible"
    >
      <div class="windows_box">
        <div class="windows_title">{{titles}}</div>
        <div class="line"></div>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
          <div class="windows_content">
            <div class="content_left" style="height: auto;">
              <el-form-item label="轮播图片" prop="img">
                <el-upload class="avatar-uploader" :file-list="fileList" v-model="ruleForm.img" list-type="picture-card"
                  :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                  :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                  <el-icon class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </div>
          </div>
          <div class="windows_content_box">
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, ElTable, ElForm } from "element-plus";
import type { Ref } from "vue";
import { reactive, onMounted, ref, watch, computed } from "vue";
import { swiperGet, swiperAdd, swiperdel } from "/@/api/public/swiper/index";
import { fileUpload } from "/@/api/login/index";
import "/src/css/business.css";
import axios from "axios";
import { Plus } from "@element-plus/icons-vue";
import { url } from "/@/api/url";

// 定义响应式数据类型
type SwiperItem = {
  id: number;
  showBoolean: boolean;
  img: string;
  updatetime: string;
};

interface UploadUserFile {
  name: string;
  url: string;
}

// 初始化响应式数据
const data = ref([] as SwiperItem[]); // 轮播图数据
const originalData = ref([] as SwiperItem[]); // 原始轮播图数据
const filteredData = ref([] as SwiperItem[]); // 过滤后的数据
const paginatedData = ref([] as SwiperItem[]); // 分页后的数据
const value1 = ref(null); // 搜索框数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的记录数
const fileList = ref<UploadUserFile[]>([]); // 上传文件列表
const total = ref(0); // 总记录数
const dialogVisible = ref(false); // 弹窗是否显示
const multipleTableRef = ref<InstanceType<typeof ElTable>>(); // 表格多选引用
const selectedRows = ref([] as SwiperItem[]) as Ref<Array<SwiperItem>>; // 多选数据
const ruleFormRef = ref<InstanceType<typeof ElForm>>(); // 表单引用
  const titles = ref("");
const ruleForm = reactive({
  img: "",
  id: "",
  show: 1,
  updatetime: "",
});

// 加载状态
const loading = ref(false);

// 表单验证规则
const rules = {
  img: [{ required: true, message: "请上传图片", trigger: ["blur", "change"] }],
};

// 组件挂载后获取数据
onMounted(() => {
  fetchData();
});

// 监听页码、页大小和过滤数据变化，自动更新分页数据
watch([currentPage, pageSize, filteredData], () => {
  updatePaginatedData();
}, { deep: true });

// 获取轮播图数据
const fetchData = () => {
  loading.value = true;
  return swiperGet({ page: currentPage.value, pageSize: pageSize.value })
    .then((res) => {
      console.log(res);
      originalData.value = res.data.map((item: any) => ({
        ...item,
        showBoolean: item.show == 1,
      }));
      data.value = [...originalData.value];
      filteredData.value = [...originalData.value];
      total.value = res.total || res.data.length; // 使用API返回的总记录数
      updatePaginatedData(); // 加载数据后更新分页
    })
    .catch((error) => {
      console.error("获取数据失败:", error);
      ElMessage.error("获取数据失败，请稍后再试！");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 处理页码变化
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  updatePaginatedData();
};
const changeSwitch = (val: any) => {
  //show等于1时，show等于0，show等于0时，show等于1
  val.show = val.show == 1 ? 0 : 1;
  console.log(val.show);

  swiperAdd(val)
    .then((res) => {
      ElMessage.success("操作成功！");
      fetchData();
    })
    .catch((error) => {
      ElMessage.error("操作失败，请稍后再试！");
    });
};
// 处理页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  updatePaginatedData();
};

let debounceTimer: NodeJS.Timeout | null = null;

// 防抖搜索
const debouncedSearch = () => {
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(search, 500);
};

// 执行搜索
const search = () => {
  // 日期清空时全部渲染
  if (!value1.value || !value1.value[0] || !value1.value[1]) {
    filteredData.value = originalData.value;
  } else {
    const startTime = new Date(value1.value[0]).getTime();
    const endTime = new Date(value1.value[1]).getTime();

    filteredData.value = originalData.value.filter((item: any) => {
      const itemTime = new Date(item.updatetime).getTime();
      return itemTime >= startTime && itemTime <= endTime;
    });
  }
  
  total.value = filteredData.value.length;
  currentPage.value = 1; // 搜索后重置到第一页
  updatePaginatedData(); // 搜索后更新分页数据
};

// 处理表格选择变化
const handleSelectionChange = (val: Array<SwiperItem>) => {
  selectedRows.value = val;
};

// 新增轮播图
const adds = () => {
  titles.value = "新增";
  dialogVisible.value = true;
  // 重置表单前清除验证状态
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate();
  }
};

// 提交表单
const submitForm = (formEl: any) => {
  if (!formEl) return;
  formEl.validate((valid: boolean) => {
    if (valid) {
      swiperAdd(ruleForm)
        .then((res: any) => {
          console.log(res);
          if (res.code === 1) {
            ElMessage.success("提交成功!");
            resetForm(formEl); // 清空表单
            dialogVisible.value = false;
            fetchData(); // 刷新数据
          }
        })
        .catch((error: any) => {
          console.error("提交表单失败:", error);
          ElMessage.error("提交失败，请稍后再试！");
        });
    } else {
      ElMessage.warning("请填写完整信息！");
      return false;
    }
  });
};

// 重置表单
const resetForm = (formEl?: any) => {
  if (formEl) {
    formEl.resetFields(); // 重置字段和验证状态
  }
  ruleForm.img = "";
  fileList.value = [];
  dialogVisible.value = false; // 关闭弹窗
};

// 图片上传成功处理
const handleAvatarSuccess = (
  response: any,
  uploadFile: File,
  fileList: UploadUserFile[]
) => {
  console.log("图片上传成功", response);
  // 上传成功后手动触发表单验证，更新提示词状态
  if (ruleFormRef.value) {
    ruleFormRef.value.validateField("img");
  }
};

// 图片上传前处理
const beforeAvatarUpload = async (rawFile: File) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  
  try {
    const form = new FormData();
    form.append("file", rawFile);
    const res = await axios({
      url: "/pc/common/upload",
      method: "POST",
      data: form,
    });
    
    console.log("图片上传接口返回", res);
    ruleForm.img = res.data.data.url;
    fileList.value = [
      {
        name: rawFile.name, // 使用原始文件名
        url: url + res.data.data.url,
      },
    ];
    
    // 上传成功后手动触发表单验证
    if (ruleFormRef.value) {
      ruleFormRef.value.validateField("img");
    }
    
    return true;
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败，请稍后再试！");
    return false;
  }
};

// 编辑轮播图
const editRow = (row: SwiperItem) => {
  titles.value = "编辑"
  dialogVisible.value = true;
  // 填充表单数据
  Object.assign(ruleForm, row);
  // 确保图片路径正确
  ruleForm.img = url + row.img;
  // 初始化 fileList
  fileList.value = [
    {
      name: row.img.split("/").pop() || "图片", // 获取文件名
      url: ruleForm.img,
    },
  ];
  
  // 编辑时清除验证状态
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate("img");
  }
};

// 批量删除
const deleteSelectedRows = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除选中的记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const idsToDelete = selectedRows.value.map((row: { id: any }) => row.id);
    const ids = idsToDelete.join(",");

    await swiperdel({ ids: ids }); // 调用 API 批量删除数据
    console.log("删除的 ID:", idsToDelete);

    ElMessage.success("删除成功！");

    // 更新本地数据
    originalData.value = originalData.value.filter(
      (item: { id: any }) => !idsToDelete.includes(item.id)
    );
    filteredData.value = filteredData.value.filter(
      (item: { id: any }) => !idsToDelete.includes(item.id)
    );
    total.value -= idsToDelete.length;

    // 清空选中状态
    selectedRows.value = [];
    multipleTableRef.value?.clearSelection();

    // 处理删除后当前页无数据的情况
    handleAfterDelete();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请稍后再试！");
  }
};

// 删除单行
const deleteRow = async (row: SwiperItem) => {
  try {
    await ElMessageBox.confirm("确定要删除这条记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await swiperdel({ ids: row.id }) as any; // 调用 API 删除单条数据

    ElMessage.success("删除成功！");

    // 更新本地数据
    originalData.value = originalData.value.filter((item: SwiperItem) => item.id !== row.id);
    filteredData.value = filteredData.value.filter((item: SwiperItem) => item.id !== row.id);
    total.value--;

    // 处理删除后当前页无数据的情况
    handleAfterDelete();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请稍后再试！");
  }
};

// 处理删除后当前页无数据的情况
const handleAfterDelete = () => {
  if (filteredData.value.length === 0 && currentPage.value > 1) {
    currentPage.value--;
    fetchData();
  } else {
    updatePaginatedData();
  }
};

// 图片预览处理
const handlePictureCardPreview = (file: UploadUserFile) => {
  console.log("预览图片:", file.url);
};

// 图片移除处理
const handleRemove = (file: UploadUserFile) => {
  ruleForm.img = "";
  // 移除图片后清除验证状态
  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate("img");
  }
  console.log("移除图片:", file.name);
};

// 更新分页数据
function updatePaginatedData() {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  paginatedData.value = filteredData.value.slice(start, end);
}
</script>

<style lang="scss">
.el-table .el-table__cell.is-center {
  position: unset !important;
}
</style>